package org.example.shiro;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.example.pojo.User;
import org.example.service.UserService;
import org.example.util.AuthAndRoleDTO;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *@Author: CJ
 *@Date: 2021-10-20 0:06
 */
@Component
@Slf4j
public class UserRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    /**
     * 授权，权限操作
     *
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(@NotNull PrincipalCollection principals) {
        log.info("------进入授权操作了------");
        User user = (User) principals.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        // 通过账号来查询相应的角色，权限数据
        List<AuthAndRoleDTO> authAndRoleDTOS = userService.selectAuthAndRole(user.getUsername());
        authAndRoleDTOS.forEach(item -> {
            log.info("查询到的权限，角色：" + item.toString());
            String roleName = item.getRoleName();
            String authCode = item.getAuthCode();
            info.addStringPermission(authCode);
            info.addRole(roleName);
        });
        return info;
    }

    /**
     * 认证操作
     *
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        log.info("------进入认证操作了------");
        // 拿到UsernamePasswordToken，它里面有用户名，密码数据
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken) token;
        // 查询数据库
        User user = userService.selectOne(usernamePasswordToken.getUsername(), String.valueOf(usernamePasswordToken.getPassword()));
        if (user == null) {
            return null;
        }
        //Session session = SecurityUtils.getSubject().getSession();
        // 更新用户登录时间，也可以在ShiroRealm里面做
        //session.setAttribute("user", user);
        return new SimpleAuthenticationInfo(user, token.getCredentials(), getName());
    }
}
